﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnityScriptEngine;
using System.Drawing.Printing;

namespace MBBHotelReservation
{
    public partial class frmRoomReservation : Form
    {
        UnityProcessor proc = new UnityProcessor();
        UnityScript[] dat = new UnityScript[0];
        Threader t = new Threader();

        List<string> itemCode = new List<string>();
        DataTable items = new DataTable();
        DataTable guest = new DataTable();
        string[] breakFast = new string[0];
        string[] breakFastCount = new string[0];
        string[] swimmingData = new string[0];
        string[] swimmingAmount = new string[0];

        float roomPrice = 0.0f, halfDay = 0.0f, breakfastPrice = 135f;
        string curRO = "", curROStamp = "", curSeries = "", halfDayCategory = "", type = "Sales", transactionMode = "Occupied";
        string wrnEntMsg = "", timeofDay = "";
        float gtotal = 0f, roomAmount = 0f, myDiscount= 0f;
        int breakfastCounter = 0, swimmingCounter = 0;

        bool npersonErr = false, prcErr = false, itmErr = false, daysErr = false,
            cmtErr = false, supErr = false, Committing = false, sErr = false, discErr = false, paymentErr = false,
            scErr = false, isViewing = false, anotherSeries = false;

        //AutoChecker
        Timer tmr = new Timer();
        frmMonitoringManager parent;
        
        public frmRoomReservation(frmMonitoringManager p)
        {
            parent = p;
            InitializeComponent();
            this.Load += new EventHandler(frmRoomReservation_Load);
            txtGuestName.TextChanged += new EventHandler(txtguestName_TextChanged);
            txtNPerson.TextChanged += new EventHandler(CheckValue);
            txtPrice.TextChanged += new EventHandler(CheckValue);
            txtASwimmingCharged.TextChanged +=new EventHandler(CheckValue);
            txtCSwimmingCharged.TextChanged += new EventHandler(CheckValue);
            txtDiscount.TextChanged += new EventHandler(CheckValue);
            txtNDays.TextChanged += new EventHandler(CheckValue);
            txtPaymentAmount.TextChanged += new EventHandler(CheckValue);
            txtNDays.LostFocus += new EventHandler(txtNDays_LostFocus);
            btnAdd.Click += new EventHandler(btnAdd_Click);
            btnCommit.Click += new EventHandler(btnCommit_Click);
            btnAdd.LostFocus += new EventHandler(delegate(object sender, EventArgs e)
            {
                txtOccupantsName.Focus();
            });
            mnuRemoveEntry.Click += new EventHandler(mnuRemoveEntry_Click);
            tmr.Interval = 500;
            tmr.Tick += new EventHandler(tmr_Tick);
            tmr.Enabled = true;
            t.MethodCompleted += new EventHandler(t_MethodCompleted);

            //unity processor
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            proc.ProcessError += new ProcessHandler(proc_ProcessError);

            //timeofday
            overnight.Click += new EventHandler(overnight_Click);
            daytime.Click += new EventHandler(daytime_Click);
            _24Hours.Click += new EventHandler(_24Hours_Click);
            chkDay.Click +=new EventHandler(chkDay_Click);
            chkNight.Click +=new EventHandler(chkNight_Click);

            //breakfast event
            beeftapa.ValueChanged +=new EventHandler(NumericValueChanged);
            tocino.ValueChanged += new EventHandler(NumericValueChanged);
            omelet.ValueChanged += new EventHandler(NumericValueChanged);
            hotdog.ValueChanged += new EventHandler(NumericValueChanged);
            daingnabangus.ValueChanged += new EventHandler(NumericValueChanged);
            cornedbeef.ValueChanged += new EventHandler(NumericValueChanged);
            longganisa.ValueChanged += new EventHandler(NumericValueChanged);
            sliceham.ValueChanged += new EventHandler(NumericValueChanged);
            Bacon.ValueChanged += new EventHandler(NumericValueChanged);

            //payment mode
            cash.Click += new EventHandler(cash_Click);
            card.Click += new EventHandler(card_Click);
            check.Click += new EventHandler(check_Click);
            chkCharge.Click += new EventHandler(chkCharge_Click);

            btnPrint.Click +=new EventHandler(btnPrint_Click);
        }

        void chkCharge_Click(object sender, EventArgs e)
        {
            if (chkCharge.Checked == true)
            {
                type = "Charged";
            }
            else
            {
                type = "Sales";
            }
        }
        void check_Click(object sender, EventArgs e)
        {
            if (check.Checked == true)
            {
                grpType.Enabled = true;
                txtBank.Text = "";
                txtCheckNumber.Text = "";
                txtDueDate.Text = "";
                txtAccountName.Text = "";
                txtBank.Focus();
            }
        }
        void card_Click(object sender, EventArgs e)
        {
            if (card.Checked == true)
            {
                grpType.Enabled = true;
                txtBank.Text = "";
                txtCheckNumber.Text = "";
                txtDueDate.Text = "";
                txtAccountName.Text = "";
                txtBank.Focus();
            }
        }
        void cash_Click(object sender, EventArgs e)
        {
            if (cash.Checked == true)
            {
                grpType.Enabled = false;
                txtBank.Text = "";
                txtCheckNumber.Text = "";
                txtDueDate.Text = "";
                txtAccountName.Text = "";
                txtOR.Focus();
            }
        }

        //events
        void txtNDays_LostFocus(object sender, EventArgs e)
        {
            
            float nValue = 1;
            if (txtNDays.Text.Equals("0")) txtNDays.Text = "1";
            float numdays = float.Parse(txtNDays.Text);
            
            if (numdays >= 1)
            {
                checkOutDateTime.Value = checkOutDateTime.Value.AddDays(numdays - nValue);
                chkNight.Checked = false;
                chkDay.Checked = false;
                float v = float.Parse(txtNDays.Text);
                if (v - (int)v != 0)
                {
                    MessageBox.Show("You have input decimal value. \r\n Please check and adjust manually the check out date and time \r\n And Choose additional rate(daytime/nighttime) ...\r\nThis is a friendly reminder...", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("Invalid Entry. \r\n This is a friendly reminder...", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtNDays.Text = "1";
                txtNDays.Focus();
            }
            
        }
        void chkNight_Click(object sender, EventArgs e)
        {
            if (chkNight.Checked == true)
            {
                chkDay.Enabled = false;
                halfDay = parent.overNightFee;
                halfDayCategory = "Overnight";
            }
            else
            {
                chkDay.Enabled = true;
                halfDay = 0f;
                halfDayCategory = "";
            }
            ComputationMethod();
        }
        void chkDay_Click(object sender, EventArgs e)
        {
            if (chkDay.Checked == true)
            {
                chkNight.Enabled = false;
                halfDay = parent.dayTimeFee;
                halfDayCategory = "Day Time";
            }
            else
            {
                chkNight.Enabled = true;
                halfDay = 0f;
                halfDayCategory = "";
            }
            ComputationMethod();
        }
        void _24Hours_Click(object sender, EventArgs e)
        {
            if (_24Hours.Checked == true)
            {
                DateTime now = DateTime.Now;
                DateTime target = DateTime.Today.AddDays(1).AddHours(12);
                double result = (target - now).TotalHours;

                checkOutDateTime.Value = DateTime.Now.AddHours(result);
                txtNDays.ReadOnly = false;
                txtNDays.Text = "1";
                roomPrice = parent.oneDayFee;
                txtNDays.Focus();

                ComplimentaryBreakfast.Enabled = true;
                grpSwimming.Enabled = true;
                additionHalfDay.Enabled = true;
                timeofDay = "24 Hours";
            }
            else
            {
                checkOutDateTime.Text = "";
                roomPrice = 0.0f;
            }
            txtPrice.Text = roomPrice.ToString("#,#0.00");
        }
        void daytime_Click(object sender, EventArgs e)
        {
            if (daytime.Checked == true)
            {
                DateTime now = DateTime.Now;
                DateTime target = DateTime.Today.AddHours(18);
                double result = (target - now).TotalHours;

                checkOutDateTime.Value = DateTime.Now.AddHours(result);
                roomPrice = parent.dayTimeFee;

                ComplimentaryBreakfast.Enabled = false;
                grpSwimming.Enabled = false;
                additionHalfDay.Enabled = false;
                timeofDay = "daytime";
                resetValues();
            }
            else
            {
                checkOutDateTime.Text = "";
                roomPrice = 0.0f;
            }
            txtPrice.Text = roomPrice.ToString("#,#0.00");
        }
        void overnight_Click(object sender, EventArgs e)
        {
            if (overnight.Checked == true)
            {
                DateTime now = DateTime.Now;
                DateTime target = DateTime.Today.AddDays(1).AddHours(8);
                double result = (target - now).TotalHours;

                checkOutDateTime.Value = DateTime.Now.AddHours(result);
                roomPrice = parent.overNightFee;

                ComplimentaryBreakfast.Enabled = false;
                grpSwimming.Enabled = false;
                additionHalfDay.Enabled = false;
                timeofDay = "overnight";
                resetValues();
            }
            else
            {
                checkOutDateTime.Text = "";
                roomPrice = 0.0f;
            }
            txtPrice.Text = roomPrice.ToString("#,#0.00");
        }
        void frmRoomReservation_Load(object sender, EventArgs e)
        {
            //Start AutoCheck timer
            if (!isViewing)
            {
                InitLookUp();
            }
            else
            {
                States(false);
                grpEntry.Visible = false;
            }
            States(false);
            txtNPerson.Text = "0";
            txtPrice.Text = "0.00";
            txtDiscount.Text = "0.00";
            resetValues();
            InitializeItemTable();
            t.MethodCall(CheckEntry);
        }
        void btnPrint_Click(object sender, EventArgs e)
        {
            PrintRegistrationForm();
        }
        void mnuRemoveEntry_Click(object sender, EventArgs e)
        {
            if (grdItems.SelectedRows.Count == 0) return;
            DialogResult dlg = MessageBox.Show("The entry will be permanently deleted from the list.\r\n" +
                "Do you wish to continue?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (dlg == System.Windows.Forms.DialogResult.No) return;
            int sel = grdItems.SelectedRows[0].Index;
            items.Rows[sel].Delete();
            t.MethodCall(CheckEntry);
        }
        void btnCommit_Click(object sender, EventArgs e)
        {
            if (float.Parse(txtNPerson.Text) != 0 && float.Parse(txtPrice.Text) != 0 && !timeofDay.Equals(""))
            {
                DialogResult dlg = MessageBox.Show("Please double check your entries before committing.\r\n" +
                    "Do you wish to continue saving?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dlg == System.Windows.Forms.DialogResult.No) return;

                Committing = true;
                States(false);
                t.MethodCall(authenticateInformation);
            }
        }
        void btnAdd_Click(object sender, EventArgs e)
        {
            if (txtOccupantsName.Text != "")
            {
                DataRow dr = items.NewRow();
                dr["Occupants Name"] = txtOccupantsName.Text;
                dr["Address"] = txtOccupantsAddress.Text;
                dr["Contact Number"] = txtOccupantsContact.Text;

                items.Rows.Add(dr);
                grdItems.FirstDisplayedScrollingRowIndex = grdItems.Rows.Count - 1;

                txtOccupantsName.Text = "";
                txtOccupantsAddress.Text = "";
                txtOccupantsContact.Text = "";
                txtOccupantsName.Focus();
                t.MethodCall(CheckEntry);
            }
        }
        void txtguestName_TextChanged(object sender, EventArgs e)
        {

            DataRow[] dr = guest.Select("fName='" + txtGuestName.Text + "'");
            if (dr.Length == 1)
            {
                txtRefNum.Text = dr[0]["fRefNum"].ToString();
                txtAddress.Text = dr[0]["fAddress"].ToString();
                txtContactNumber.Text = dr[0]["fContactNum"].ToString();

                txtGuestName.ForeColor = Color.Black;
                txtRefNum.ForeColor = Color.Black;
                txtAddress.ForeColor = Color.Black;
                txtContactNumber.ForeColor = Color.Black;

                txtRefNum.ReadOnly = true;
                txtAddress.ReadOnly = true;
                txtContactNumber.ReadOnly = true;

                lblWarning.Text = "";
                supErr = false;
            }
            else //if (txtguestName.Text.Length > 0)
            {
                if (!supErr)
                {
                    txtRefNum.Text = "N/A";
                    txtAddress.Text = "N/A";
                    txtContactNumber.Text = "N/A";
                    txtGuestName.ForeColor = Color.Red;
                    txtRefNum.ForeColor = Color.Red;
                    txtAddress.ForeColor = Color.Red;
                    txtContactNumber.ForeColor = Color.Red;

                    txtRefNum.ReadOnly = false;
                    txtAddress.ReadOnly = false;
                    txtContactNumber.ReadOnly = false;

                    lblWarning.Text = "Warning: guest not found in the database.";
                    supErr = true;
                }
            }
            t.MethodCall(CheckEntry);

        }

        //Process Ended
        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {

                MessageBox.Show(desc);
                States(true);
                switch (id)
                {
                    case "COMMIT":
                        Committing = false;
                        break;
                }
                tmr.Enabled = true;
            });
        }
        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "TestDateConflict":
                        UnityScript [] conflictScript = new UnityScript[0];
                        proc.DBPUX_Data_Fetch(out conflictScript);
                        
                        if (conflictScript[0].Data_Count > 0)
                            MessageBox.Show("The room is not available please check your check in date or check out date");
                        else
                            t.MethodCall(CommitReservation);
                        break;
                    case "INITGEN":
                        //t.MethodCall(LoadData);
                        break;
                    case "GENERATE":
                    case "INIT":
                        proc.DBPUX_Data_Fetch(out dat);
                        //This is to insert initial data to purchaseordergenerate table.
                        UnityElement ronum;
                        dat[0].Data_Get(1, out ronum);

                        int curDbNum = int.Parse(ronum.Data_GetField(0).ToString());
                        curSeries = ronum.Data_GetField(1).ToString();
                        curRO = curSeries + (curDbNum).ToString("#0000");
                        if (curDbNum == 999)
                        {
                            curSeries += "R";
                            anotherSeries = true;
                        }
                        curROStamp = ronum.Data_Stamp;
                        txtRONum.Text = curRO;

                        if (id == "GENERATE") break;
                        guest = dat[1].ToDataTable();
                        if (!txtGuestName.Focused)
                        {
                            txtGuestName.AutoCompleteCustomSource.AddRange(dat[1].ToList<string>(1));
                        }
                        txtRoomNumber.Text = parent.room;
                        break;
                    case "COMMIT":
                        //printing form
                        this.Close();
                        break;
                };
                if (Committing || isViewing) return;
                tmr.Enabled = true;
                States(true);
            });
        }
        void t_MethodCompleted(object sender, EventArgs e)
        {
            t.SafeCall(this, delegate
            {
                switch (sender.ToString())
                {
                    case "CheckEntry":
                        lblWarningEntry.Text = wrnEntMsg;
                        if (npersonErr)
                            txtNPerson.ForeColor = Color.Red;
                        else
                            txtNPerson.ForeColor = Color.Black;

                        if (prcErr)
                            txtPrice.ForeColor = Color.Red;
                        else
                            txtPrice.ForeColor = Color.Black;

                        if (daysErr)
                            txtNDays.ForeColor = Color.Red;
                        else
                            txtNDays.ForeColor = Color.Black;

                        if (sErr)
                            txtASwimmingCharged.ForeColor = Color.Red;
                        else
                            txtASwimmingCharged.ForeColor = Color.Black;

                        if (scErr)
                            txtCSwimmingCharged.ForeColor = Color.Red;
                        else
                            txtCSwimmingCharged.ForeColor = Color.Black;

                        if (discErr)
                            txtDiscount.ForeColor = Color.Red;
                        else
                            txtDiscount.ForeColor = Color.Black;

                        if (paymentErr)
                            txtPaymentAmount.ForeColor = Color.Red;
                        else
                            txtPaymentAmount.ForeColor = Color.Black;

                        if (!npersonErr && !prcErr && !itmErr && !sErr && !scErr && !discErr)
                        {
                            btnAdd.Visible = true;
                            ComputationMethod();
                        }
                        else
                        {
                            btnAdd.Visible = false;
                        }

                        btnCommit.Visible = !cmtErr;
                        
                        break;
                    case "CheckContent":
                        btnCommit.Visible = !cmtErr;
                        break;
                }
                if (Committing) return;
                tmr.Enabled = true;
            });
        }

        //Operations
        void CheckValue(object sender, EventArgs e)
        {
            t.MethodCall(CheckEntry);
        }
        void NumericValueChanged(object sender, EventArgs e)
        {
            ComputationMethod();
        }
        void InitializeItemTable()
        {
            items.Columns.Add("Occupants Name");
            items.Columns.Add("Address");
            items.Columns.Add("Contact Number");

            grdItems.DataSource = items;
            grdItems.Columns[0].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            grdItems.Columns[1].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            grdItems.Columns[2].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
        }
        void InitLookUp()
        {
            while (proc.IsRunning)
            {
                System.Threading.Thread.Sleep(1);
            }
            UnityScript u = new UnityScript("INIT", 4);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblgenerate");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblprofile");
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void CheckEntry()
        {
            float fnperson = 0f, fprice = 0f, fswimmingCharge = 0f, fNDay = 0f, fcswimmingCharge = 0f, fDiscount = 0f, fPaymentAmount = 0f;
            string np = txtNPerson.Text, price = txtPrice.Text, cswimming = txtCSwimmingCharged.Text,swimming = txtASwimmingCharged.Text, nday = txtNDays.Text, discount = txtDiscount.Text, paymentAmt = txtPaymentAmount.Text;
            //Check if Commit is valid
            if (txtGuestName.Text.Length != 0 && items.Rows.Count != 0)
            {
                cmtErr = false;
            }
            else
            {
                cmtErr = true;
            }
            //Check Payment Amount
            if (!float.TryParse(paymentAmt, out fPaymentAmount))
            {
                paymentErr = true;
                wrnEntMsg = "Invalid Payment Amount value detected!\r\n";
            }
            else
            {
                paymentErr = false;
                if (!paymentErr) wrnEntMsg = "";
            }
            //Check Number of Person
            if (!float.TryParse(np, out fnperson))
            {
                npersonErr = true;
                wrnEntMsg = "Invalid Number of Person value detected!\r\n";
            }
            else
            {
                npersonErr = false;
                if (!npersonErr) wrnEntMsg = "";
            }
            //Check Price
            if (!float.TryParse(price, out fprice))
            {
                prcErr = true;
                wrnEntMsg += "Invalid PRICE value detected!\r\n";
            }
            else
            {
                prcErr = false;
                if (!prcErr) wrnEntMsg = "";
            }
            //Check Swimming Price
            if (!float.TryParse(swimming, out fswimmingCharge))
            {
                sErr = true;
                wrnEntMsg += "Invalid Swimming Price value detected!\r\n";
            }
            else
            {
                sErr = false;
                if (!sErr) wrnEntMsg = "";
            }
            //Check Swimming Price
            if (!float.TryParse(cswimming, out fcswimmingCharge))
            {
                scErr = true;
                wrnEntMsg += "Invalid Swimming Price value detected!\r\n";
            }
            else
            {
                scErr = false;
                if (!scErr) wrnEntMsg = "";
            }
            //Check Number of Days
            if (!float.TryParse(nday, out fNDay))
            {
                daysErr = true;
                wrnEntMsg += "Invalid Number of Days value detected!\r\n";
            }
            else
            {
                daysErr = false;
                if (!daysErr) wrnEntMsg = "";
            }
            //Check Discount
            if (!float.TryParse(discount, out fDiscount))
            {
                discErr = true;
                wrnEntMsg += "Invalid Discount value detected!\r\n";
            }
            else
            {
                discErr = false;
                if (!discErr) wrnEntMsg = "";
            }
        }
        void authenticateInformation()
        {
            //test all data before saving
            //guest information
            if (txtRefNum.Text != "")
            {
                //reservation information
                if (txtRONum.Text != "")
                {
                    //check the database for any conflicts on the check in and check out date
                    UnityScript conflict = new UnityScript("TestDateConflict", 13);

                    string inDateTime = checkInDateTime.Value.ToString("yyyy-MM-dd HH:mm:00");
                    string outDateTime = checkInDateTime.Value.ToString("yyyy-MM-dd HH:mm:00");

                    if (checkInDateTime.Value > DateTime.Now)
                        transactionMode = "Reserve";
                    else
                        transactionMode = "Occupied";

                    conflict.Script_Add(Script.PROC_NAME, "TestDateConflict");
                    conflict.Script_Add(Script.DBPUX_BEGIN);
                    conflict.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblRoomAccomodation WHERE fRoomNumber = '" + txtRoomNumber.Text + "'"
                        + "AND (fTransactionMode = 'Reserve' OR fTransactionMode = 'Occupied' OR fTransactionMode = 'Maintenance')"
                        + "AND ((fCheckInDateTime BETWEEN '" + inDateTime + "' AND '" + outDateTime + "') OR (fCheckOutDateTime BETWEEN '" + inDateTime + "' AND '" + outDateTime + "'))");
                    conflict.Script_Add(Script.DBPUX_COMMIT);
                    proc.Run(conflict);
                }
                else
                {
                    MessageBox.Show("Reservation Information Incomplete", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("Guest Information Incomplete", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        void CommitReservation()
        {

            //Construct Room Accomodation Details.
            UnityScript u = new UnityScript("COMMIT", 13);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_INSERT, "tblroomaccomodation(fRegistrationNumber, fRefNum, fDate, fRoomNumber,"+
                        "fNPerson, fTimeOfDay, fNDays,"+
                        "fCheckInDateTime, fCheckOutDateTime, fHalfDayCategory, fDiscountGiven, fTransactionMode, fType )",
                new string[]{
                    txtRONum.Text, txtRefNum.Text, DateTime.Now.ToString("yyyy-MM-dd"), txtRoomNumber.Text,
                    int.Parse(txtNPerson.Text).ToString(), timeofDay, float.Parse(txtNDays.Text).ToString(),
                    checkInDateTime.Value.ToString("yyyy-MM-dd HH:mm:00"), checkOutDateTime.Value.ToString("yyyy-MM-dd HH:mm:00"),
                    halfDayCategory, float.Parse(txtDiscount.Text).ToString(), transactionMode, type
                });

            //Construct Occupants Items.
            /*
            for (int i = 0; i < items.Rows.Count; i++)
            {
                u.Script_Add(Script.DBPUX_INSERT, "tblpurchaseorderitems(fNumber, fBarcode, fQty, fPrice)",
                    new string[]{
                        txtRONum.Text,
                        itemCode[i],
                        items.Rows[i]["Qty"].ToString(),
                        items.Rows[i]["Price"].ToString()
                    });
            }
            */
            //Update PO Number
            if (!anotherSeries)
            {
                u.Script_Add(Script.DBPUX_UPDATE, "tblgenerate SET " +
                    "fCurNum=fCurNum+1"
                    ,
                    "(fID='2') AND (fStamp='" + curROStamp + "')");
            }
            else
            {
                u.Script_Add(Script.DBPUX_UPDATE, "tblgenerate SET " +
                    "fCurNum='0', fCurSeries='" + curSeries + "'"
                    ,
                    "(fID='2') AND (fStamp='" + curROStamp + "')");
            }
            //Transaction Log
            /*
            u.Script_Add(Script.DBPUX_INSERT, "tblpurchaseorderlog(fUser, fMsg, fDate)",
                new string[]{
                    "Added " + txtRONum.Text + " worth " + gtotal.ToString("#,#0.00"),
                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                });
             */ 
            u.Script_Add(Script.DBPUX_COMMIT);
            //Wait if UnityCall is in progress.
            System.Threading.Thread.Sleep(10);
            while (proc.IsRunning)
            {

            }
            proc.Run(u);
        }
        void resetValues()
        {
            
            txtASwimmingCharged.Text = "0.00";
            txtCSwimmingCharged.Text = "0.00";
            txtNDays.Text = "0";
            txtNDays.ReadOnly = true;
        }
        void States(bool s)
        {
            grpDetails.Enabled = s;
            grpEntry.Enabled = s;
            grdItems.Enabled = s;
        }
        void tmr_Tick(object sender, EventArgs e)
        {
            tmr.Enabled = false;
            if (Committing) return;
            //Calls that involves UnityProcessor.
            if (!proc.IsRunning)
            {
                t.MethodCall(delegate
                {
                    while (proc.IsRunning)
                    {
                        System.Threading.Thread.Sleep(1);
                    }
                    UnityScript u = new UnityScript("GENERATE", 4);
                    u.Script_Add(Script.DBPUX_BEGIN);
                    u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblgenerate"); ;
                    u.Script_Add(Script.DBPUX_COMMIT);
                    proc.Run(u);
                });
            }

            //Calls that does not involve UnityProcessor.
            //if (txtQty.Text != "") 
            //t.MethodCall(CheckEntry);
            //t.MethodCall(CheckContent);
        }
        void ComputationMethod()
        {
            //compute for total room accomodation
            if (txtNDays.Text.Equals("")) txtNDays.Text = "0";
            int ndays = (int)float.Parse(txtNDays.Text);
            if (ndays == 0) ndays = 1;
            if (txtDiscount.Text.Equals("")) txtDiscount.Text = "0";

            myDiscount = float.Parse(txtDiscount.Text);
            float roomPrice = float.Parse(txtPrice.Text);
            roomAmount = roomPrice * ndays + halfDay;
            txtRoomTotal.Text = roomAmount.ToString("#,#0.00");
            //breakfast list and computation
            float breakfastAmount = 0f;
            float swimmingTotalAmount = 0f;
            float grandTotal = 0f;
            if (_24Hours.Checked == true)
            {
                breakfastList();
                
                if (breakfastCounter > 2)
                {
                    breakfastAmount = (breakfastCounter - 2) * breakfastPrice;
                }
                else
                {
                    breakfastAmount = 0;
                }
                txtExtraComplementary.Text = breakfastAmount.ToString("#,#0.00");

                //swimming list
                swimmingList();
                
                if (swimmingCounter > 2)
                {
                    swimmingTotalAmount += (float.Parse(swimmingData[0].ToString()) ) * float.Parse(swimmingAmount[0].ToString());
                    swimmingTotalAmount += (float.Parse(swimmingData[1].ToString()) - 2) * float.Parse(swimmingAmount[1].ToString());
                }
                else
                {
                    swimmingTotalAmount = 0;
                }
                txtExtraSwimming.Text = swimmingTotalAmount.ToString("#,#0.00");
            }
            grandTotal = roomAmount + swimmingTotalAmount + breakfastAmount - myDiscount;
            txtGrandTotal.Text = grandTotal.ToString("#,#0.00");
        }
        void breakfastList()
        {
            breakFast = new string[0];
            breakFastCount = new string[0];
            breakfastCounter = 0;
            foreach (Control c in ComplimentaryBreakfast.Controls)
            {
                if (c is NumericUpDown)
                {
                    NumericUpDown chk = (NumericUpDown)c;
                    float n = float.Parse(chk.Value.ToString());
                 
                    Array.Resize<string>(ref breakFastCount, breakFastCount.Length + 1);
                    Array.Resize<string>(ref breakFast, breakFast.Length + 1);
                    breakFast[breakFast.Length - 1] = chk.Text;
                    breakFastCount[breakFastCount.Length - 1] = n.ToString();
                    breakfastCounter+=(int)n;
                }
            }
        }
        void swimmingList()
        {
            swimmingData = new string[0];
            swimmingAmount = new string[0];
            swimmingCounter = 0;

            foreach (Control c in grpSwimming.Controls)
            {
                if (c is NumericUpDown)
                {
                    NumericUpDown chk = (NumericUpDown)c;
                    float n = float.Parse(chk.Value.ToString());
                    
                    Array.Resize<string>(ref swimmingData, swimmingData.Length + 1);
                    Array.Resize<string>(ref swimmingAmount, swimmingAmount.Length + 1);
                    swimmingData[swimmingData.Length - 1] = chk.Text;
                    if(chk.Name =="adult")
                        swimmingAmount[swimmingAmount.Length - 1] = txtASwimmingCharged.Text;
                    else
                        swimmingAmount[swimmingAmount.Length - 1] = txtCSwimmingCharged.Text;

                    swimmingCounter += (int)n;
                    
                }
            }
        }

        //Printing Module
        int i = 0;
        int pp = 1;

        void PrintRegistrationForm()
        {
            PrintDocument pd = new PrintDocument();
            pd.DocumentName = "Registration Form";
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = pd;
            // Set the page orientation to landscape.
                //pd.DefaultPageSettings.Landscape = true;
                //pd.DefaultPageSettings.PaperSize = new PaperSize("Folio", 850, 1300);
            //pd.DefaultPageSettings.PaperSize.Width = 1300;
            //pd.DefaultPageSettings.PaperSize.Height = 850;
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                pp = 1;
                i = 0;
                ppdlg.Document = pd;
                ppdlg.ShowDialog();
            }

        }
        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float lpp = 0;
            float y = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.PageBounds.Left + 50;
            float lw = e.PageBounds.Width - 50;
            float th = e.PageBounds.Height - 100;
            float bm = e.PageBounds.Bottom - 100;
            float tHt = 0;
            float ht = 0;

            Font cFont;
            StringFormat sf = new StringFormat();
            //Title
            cFont = new Font("Arial", 16f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            y = 50;

            e.Graphics.DrawImage(pictureBox2.Image, 100, 35);
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString("Malolos Resort Club Royale ", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //SubTitle
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            y += tHt;
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("McArthur Highway, Mabolo, Malolos, Bulacan", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //SubTitle
            y += tHt;
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("Tel. No. (044) 791-03-78     Fax. No. (044) 796-01-31", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //SubTitle
            y += tHt;
            y += tHt;
            cFont = new Font("Arial", 13f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("Registration Form ", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //Line
            y += tHt;
            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y), new PointF(lw, y));

            y += tHt;
            //Guest Information
            sf.Alignment = StringAlignment.Near;
            
            y += tHt;
            //Registration Number
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            e.Graphics.DrawString("Registration Number: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            e.Graphics.DrawString("" + txtRONum.Text, cFont, Brushes.Black, lm + 240, y, sf);

            y += tHt;
            //Reference Number
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            e.Graphics.DrawString("Reference Number: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            e.Graphics.DrawString("" + txtRefNum.Text, cFont, Brushes.Black, lm + 240, y, sf);

            y += tHt;
            //Guest or Corporate Name
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            e.Graphics.DrawString("Guest / Corporate Name: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            e.Graphics.DrawString("" + txtGuestName.Text, cFont, Brushes.Black, lm + 240, y, sf);

            y += tHt;
            //Address
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            e.Graphics.DrawString("Address: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            e.Graphics.DrawString("" + txtAddress.Text, cFont, Brushes.Black, lm + 240, y, sf);

            y += tHt;
            //Contact Number
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            e.Graphics.DrawString("Contact Number: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            e.Graphics.DrawString("" + txtContactNumber.Text, cFont, Brushes.Black, lm + 240, y, sf);

            y += tHt;
            y += tHt;
            
            //Room Accomodation Details
            cFont = new Font("Arial", 11f, FontStyle.Bold);
            e.Graphics.DrawString("Room Accomodation Details ", cFont, Brushes.Black, lm + 5, y, sf);

            y += tHt;
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            e.Graphics.DrawString("Room Number ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            e.Graphics.DrawString("" + txtRoomNumber.Text, cFont, Brushes.Black, lm + 240, y, sf);

            y += tHt;
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            e.Graphics.DrawString("Time of the day ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            e.Graphics.DrawString("" + timeofDay, cFont, Brushes.Black, lm + 240, y, sf);

            y += tHt;
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            e.Graphics.DrawString("Check In Date and Time ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            e.Graphics.DrawString("" + checkInDateTime.Value , cFont, Brushes.Black, lm + 240, y, sf);

            y += tHt;
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            e.Graphics.DrawString("Check Out Date and Time ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            e.Graphics.DrawString("" + checkOutDateTime.Value, cFont, Brushes.Black, lm + 240, y, sf);

            y += tHt;
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            e.Graphics.DrawString("Number of Days: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            e.Graphics.DrawString("" + txtNDays.Text, cFont, Brushes.Black, lm + 240, y, sf);

            y += tHt;
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            e.Graphics.DrawString("Number of Person: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            e.Graphics.DrawString("" + txtNPerson.Text, cFont, Brushes.Black, lm + 240, y, sf);

            y += tHt;
            y += tHt;

            //Occupants List

            cFont = new Font("Arial", 11f, FontStyle.Underline);
            e.Graphics.DrawString("Occupant's Name ", cFont, Brushes.Black, lm + 5, y, sf);

            //Complimentary Breakfast

            cFont = new Font("Arial", 11f, FontStyle.Underline);
            e.Graphics.DrawString("Complementary Breakfast ", cFont, Brushes.Black, lm + 400, y, sf);

            //Occupants List and Breakfast
            for (int i = 0; i < grdItems.Rows.Count; i++)
            {
                y += tHt;
                cFont = new Font("Arial", 11f, FontStyle.Regular);
                e.Graphics.DrawString((i+1) + ".  "+grdItems.Rows[i].Cells[0].Value.ToString() , cFont, Brushes.Black, lm + 5, y, sf);

                e.Graphics.DrawString((i + 1) + ".  " + grdItems.Rows[i].Cells[0].Value.ToString(), cFont, Brushes.Black, lm + 400, y, sf);
            }

            y += tHt;
            y += tHt;


            //Swimming Entrance

            cFont = new Font("Arial", 11f, FontStyle.Bold);
            e.Graphics.DrawString("Swimming Entrance ", cFont, Brushes.Black, lm + 5, y, sf);

            y += tHt;
            y += tHt;



            //Billing Statement
            
            cFont = new Font("Arial", 11f, FontStyle.Bold);
            e.Graphics.DrawString("Billing Statement ", cFont, Brushes.Black, lm + 5, y, sf);

            y += tHt;
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            e.Graphics.DrawString("Room Price ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString("" + roomPrice.ToString("#,#0.00"), cFont, Brushes.Black, lm + 350, y, sf);

            y += tHt;
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Additional Half Day Amount: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString("" + halfDay.ToString("#,#0.00"), cFont, Brushes.Black, lm + 350, y, sf);

            y += tHt;
            y += tHt;
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Room Accomodation Amount: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString("" + roomAmount.ToString("#,#0.00"), cFont, Brushes.Black, lm + 350, y, sf);

            y += tHt;
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Additional Complimentary Breakfast: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString("" + txtExtraComplementary.Text, cFont, Brushes.Black, lm + 350, y, sf);

            y += tHt;
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Additional Swimming Entrance: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString("" + txtExtraSwimming.Text, cFont, Brushes.Black, lm + 350, y, sf);

            y += tHt;
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Discount Given: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString("" + txtDiscount.Text, cFont, Brushes.Black, lm + 350, y, sf);

            y += tHt;
            y += tHt;
            cFont = new Font("Arial", 11f, FontStyle.Bold);
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Grand Total: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString("" + txtGrandTotal.Text, cFont, Brushes.Black, lm + 350, y, sf);
           
        }
    }
}
